import { Shape } from './'
import { Point2D } from '../point'
import { computeBoundingRect } from '../helper/shape'

export default class Rect extends Shape {
  x: number
  y: number
  width: number
  height: number
  fillColor: string

  constructor(x: number, y: number, width: number, height: number, fillColor = 'black') {
    super()
    this.x = x
    this.y = y
    this.width = width
    this.height = height
    this.fillColor = fillColor
  }

  draw(ctx: CanvasRenderingContext2D): void {
    this.boundingRect = computeBoundingRect(this)
    ctx.beginPath()
    ctx.save()
    ctx.fillStyle = this.fillColor
    ctx.fillRect(this.x, this.y, this.width, this.height)
    ctx.restore()
  }

  isPointInClosedRegion(point: Point2D): boolean {
    return point.x >= this.x && point.x <= this.x + this.width && point.y >= this.y && point.y <= this.y + this.height
  }

  setPosition(position: Point2D): void
  setPosition(x: number, y: number): void
  setPosition(x: any, y?: any): void {
    if (x instanceof Point2D || Object.prototype.toString.call(x) === '[object Object]') {
      if (x.hasOwnProperty('x') && x.hasOwnProperty('y')) {
        this.x = x.x
        this.y = x.y
        Shape.update = this.id
        return
      }
    } else {
      if (typeof x === 'number') {
        this.x = x
        this.y = y
        Shape.update = this.id
      }
    }
  }
}
